package base.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Author: shen qi han
 * Date: 2022/3/21 下午4:53
 */
public class ReentrantReadWriteLockMain implements Runnable {

    /**
     * 读写锁
     */
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 先实例化一个 读写锁，然后 使用其中的 读锁(静态内部类)
     * 读锁
     */
    ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();


    @Override
    public void run() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " " + " get read lock.");
            TimeUnit.MILLISECONDS.sleep(2000);
            System.out.println("finish.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            readLock.unlock();
        }
    }

    /**
     * 读读共享并发
     */
    public void readReadConcurrent(){
        int num = 2;
        ReentrantReadWriteLockMain task = new ReentrantReadWriteLockMain();
        ExecutorService pool = Executors.newFixedThreadPool(num);
        pool.submit(task);
        pool.submit(task);
        pool.shutdown();
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockMain main = new ReentrantReadWriteLockMain();
        main.readReadConcurrent();

    }


}
